package com.zh.utils;

import com.zh.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
@Component // 注入到spring容器中
public class HtmlParseUtil {

//    public static void main(String[] args) throws IOException {
//      new HtmlParseUtil().parseJD("心理学").forEach(System.out::println);
//    }

    /**
     * 封装爬虫工具类
     * @param keyword
     * @return
     */
    public List<Content> parseJD(String keyword) throws IOException {
        List<Content> contents = new ArrayList<>();
        String url = "https://search.jd.com/Search?keyword="+keyword;

        Document document = Jsoup.parse(new URL(url), 30000);
        Element element = document.getElementById("J_goodsList");
        Elements elements = element.getElementsByTag("li");
        for (Element el : elements) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");//获取图片路径
            String price = el.getElementsByClass("p-price").eq(0).text();  // 价钱
            String title = el.getElementsByClass("p-name").eq(0).text();  // 价钱
            Content content = new Content();
            content.setImg(img);
            content.setPrice(price);
            content.setTitle(title);
            contents.add(content);
        }
        return contents;
    }
}















